package com.theten52.dev.code.fragment.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * Zookeeper 简单示例
 */
public class ZooKeeperDemo {

    public static void main(String[] args) throws Exception {
        String address = "127.0.0.1:2181";
        RetryNTimes retryNTimes = new RetryNTimes(10, 5000);

        CuratorFramework client = CuratorFrameworkFactory.newClient(address, retryNTimes);
        client.start();// 连接

        // 获取子节点，顺便监控子节点
        List<String> children = client
                .getChildren()
                .usingWatcher((CuratorWatcher) event -> System.out.println("监控： " + event)).forPath("/");

        System.out.println(children);


        Stat stat = client.checkExists().forPath("/test");
        if (stat != null) {
            // 删除节点
            client.delete().withVersion(-1).forPath("/test");
            System.out.println(stat);
        }

        // 创建节点
        String result = client
                .create()
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/test", "Data".getBytes());
        System.out.println(result);

        // 设置节点数据
        client.setData().forPath("/test", "111".getBytes());
        client.setData().forPath("/test", "222".getBytes());

        // 删除节点
        //System.out.println(client.checkExists().forPath("/test"));
        client.close();
        System.out.println("OK！");
    }
}
